﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SynoManager.DownloadStation.Subscriptions
{
    public partial class SubscriptionsGuiTab : UserControl
    {
        private readonly SubscriptionsGuiPlugin plugin;

        public SubscriptionsGuiTab()
        {
            InitializeComponent();
            this.Text = "RSS Subscriptions";
        }

        public SubscriptionsGuiTab(SubscriptionsGuiPlugin plugin)
            :this()
        {
            this.plugin = plugin;

            LoadSubscriptions();
        }

        #region Subscription List
        private void LoadSubscriptions()
        {
            subscriptionsListView.Items.Clear();
            foreach(Subscription subscription in plugin.Manager)
            {
                AddToList(subscription);
            }
        }

        private void addFeedToolStripButton_Click(object sender, EventArgs e)
        {
            SubscriptionSettingsForm form = new SubscriptionSettingsForm();
            if (form.ShowDialog(this) == DialogResult.OK)
            {
                Subscription subscription = form.Subscription;
                AddToList(subscription);
                plugin.Manager.Add(subscription);
            }
        }

        private void AddToList(Subscription subscription)
        {
            ListViewItem lvi = subscriptionsListView.Items.Add(subscription.Title);
            lvi.SubItems.Add(subscription.LastCheck.ToShortDateString() + " " +
                             subscription.LastCheck.ToShortTimeString());
            lvi.Tag = subscription;
        }

        private void editToolStripButton_Click(object sender, EventArgs e)
        {
            if (subscriptionsListView.SelectedItems.Count != 1)
                return;

            ListViewItem lvi = subscriptionsListView.SelectedItems[0];
            Subscription subscription = (Subscription) lvi.Tag;

            SubscriptionSettingsForm form = new SubscriptionSettingsForm();
            form.Subscription = subscription;

            if (form.ShowDialog(this) == DialogResult.OK)
            {
                plugin.Manager.Save();
                lvi.SubItems[0].Text = subscription.Title;
                lvi.SubItems[1].Text = subscription.LastCheck.ToShortDateString() + " " +
                                       subscription.LastCheck.ToShortTimeString();
            }
        }

        private void deleteToolStripButton_Click(object sender, EventArgs e)
        {
            foreach(ListViewItem lvi in subscriptionsListView.SelectedItems)
            {
                Subscription subscription = (Subscription) lvi.Tag;
                plugin.Manager.Remove(subscription);
                lvi.Remove();
            }
        }

        private void checkFeedsToolStripButton_Click(object sender, EventArgs e)
        {
            plugin.Manager.CheckAll();
            UpdateLastCheckTimes();
        }

        private void subscriptionsListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            editToolStripButton.Enabled = deleteToolStripButton.Enabled = (subscriptionsListView.SelectedItems.Count == 1);
            
            if (subscriptionsListView.SelectedItems.Count ==1)
            {
                ListViewItem lvi = subscriptionsListView.SelectedItems[0];
                Subscription subscription = (Subscription) lvi.Tag;
                ShowSubscription(subscription);
            }
        }
        #endregion

        #region Subscription Viewer
        private Subscription selectedSubscription;
        private void ShowSubscription(Subscription subscription)
        {
            selectedSubscription = subscription;
            feedItemsListBox.Items.Clear();

            checkCurrentToolStripButton.Enabled =
                feedItemsListBox.Enabled = true;

            feedItemsListBox.Items.Clear();
            feedItemsListBox.Items.AddRange(subscription.Items);

            splitContainer2.Panel2Collapsed = true;
        }

        private void checkCurrentToolStripButton_Click(object sender, EventArgs e)
        {
            plugin.Manager.Check(selectedSubscription);
            ShowSubscription(selectedSubscription); // refresh list
        }

        private void downloadSelectedItemToolStripButton_Click(object sender, EventArgs e)
        {
            if (feedItemsListBox.SelectedItems.Count == 0)
                return;

            foreach(SubscriptionItem item in feedItemsListBox.SelectedItems)
            {
                bool success = plugin.Manager.Download(item);
                if (!success)
                    MessageBox.Show(this, "The item could not be downloaded (download link could not be found)",
                                    "Subscription Manager", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void feedItemsListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            downloadSelectedItemToolStripButton.Enabled = feedItemsListBox.SelectedItems.Count > 0;
        }
        #endregion

        private void feedItemsListBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();

            if (e.Index >= 0)
            {
                SubscriptionItem item = (SubscriptionItem) feedItemsListBox.Items[e.Index];
                Graphics g = e.Graphics;

                System.Drawing.Font boldFont = new Font(Font, FontStyle.Bold);
                StringFormat elepsis = (StringFormat) StringFormat.GenericDefault.Clone();
                elepsis.FormatFlags |= StringFormatFlags.LineLimit;
                elepsis.Trimming = StringTrimming.EllipsisWord;

                Image image;
                switch(item.State)
                {
                    case SubscriptionItemState.Unknown:
                        image = Properties.Resources.feed;
                        break;
                    case SubscriptionItemState.Error:
                        image = Properties.Resources.feed_error;
                        break;
                    case SubscriptionItemState.Downloaded:
                        image = Properties.Resources.feed_go;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
                g.DrawImage(image, e.Bounds.Left + 2, e.Bounds.Top + 2);
                g.DrawString(item.Title, boldFont, Brushes.Black, e.Bounds.Left + 22, e.Bounds.Top + 2);
                g.DrawString(item.Description, Font, Brushes.Black, new RectangleF(e.Bounds.Left + 22, e.Bounds.Top + 18, e.Bounds.Width - 22, 20), elepsis);

                g.DrawLine(Pens.Silver, e.Bounds.Left, e.Bounds.Bottom - 1, e.Bounds.Right, e.Bounds.Bottom - 1);
                e.DrawFocusRectangle(); // do not draw if nothing is selected
            }
        }

        private void autoCheckTimer_Tick(object sender, EventArgs e)
        {
            plugin.Manager.AutoCheck();
            UpdateLastCheckTimes();
        }

        private void UpdateLastCheckTimes()
        {
            foreach(ListViewItem lvi in subscriptionsListView.Items)
            {
                Subscription subscription = (Subscription) lvi.Tag;
                lvi.SubItems[1].Text = subscription.LastCheck.ToShortDateString() + " " +
                                       subscription.LastCheck.ToShortTimeString();
            }
        }
    }
}
